package com.zygh.dlqwservice.module.controller.app;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zygh.dlqwservice.common.anno.ViLog;
import com.zygh.dlqwservice.common.domain.ResultBeans;
import com.zygh.dlqwservice.common.domain.ResultUtils;
import com.zygh.dlqwservice.common.en.Constant;
import com.zygh.dlqwservice.common.en.Month;
import com.zygh.dlqwservice.config.CorrdinateUtils;
import com.zygh.dlqwservice.constant.SwaggerTagConst;
import com.zygh.dlqwservice.module.entity.*;
import com.zygh.dlqwservice.module.entity.vo.SignVo;
import com.zygh.dlqwservice.module.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.postgis.Point;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * @author lee
 */
@RequestMapping("/sign")
@RestController
@Api(tags = SwaggerTagConst.Admin.MANAGER_APP_SIGN)
public class AppSignController {
    @Resource
    private ISignService iSignService;
    @Resource
    private IDeptService iDeptService;
    @Resource
    private ISchedulService iSchedulService;
    @Resource
    private IJobsService iJobsService;
    @Resource
    private ISysUserService iSysUserService;
    @ApiOperation("日常勤务签到")
    @PostMapping("/in")
    @ViLog(logType = "1",module =SwaggerTagConst.Admin.MANAGER_APP_SIGN,content = "日常勤务签到")
    public ResultBeans sign(@RequestBody SignVo signVo) throws Exception {
        //推送长峰科技
        pushCfkj(signVo);
        //先判断是否已经签到
        if(isSign(signVo)){
            return ResultUtils.resultBeansError("您已签到");
        }
        //没有gps坐标直接返回错误
        if(null == signVo.getSignInGps() ){
            return ResultUtils.resultBeansError("获取不到gps");
        }
        //设置签到时间为当前时间
        signVo.setSignintime(DateUtil.now());
        //获取签到时间
        String signTime = signVo.getSignintime();
        DateTime parse = DateUtil.parse(signTime);
        //签到最终时间看是否在签到签退时间内
        DateTime endDate = DateUtil.offsetMinute(parse, -Constant.Hour.halfHour.getMinute());
        //签到开始时间看是否在签到签退时间内
        DateTime startDate = DateUtil.offsetMinute(parse, Constant.Hour.halfHour.getMinute());
        //判断季节是冬季还是夏季
        String season = getSeason();
        Schedul schedul = iSchedulService.getOne(Wrappers.<Schedul>lambdaQuery().eq(Schedul::getPost, signVo.getJobName())
                .ge(Schedul::getEndTime, endDate.toTimeStr())
                .le(Schedul::getStartTime, startDate.toTimeStr())
                .like(Schedul::getSeason,season));
        if(null == schedul){
            return ResultUtils.resultBeansError("不在签到时间内");
        }
        Point point = CorrdinateUtils.formatPoint(signVo.getSignInGps());
        signVo.setGps(point);
        //签到状态
        signVo.setState(1);
        //判断是否迟到
        int clock = parse.compareTo(DateUtil.parse(DateUtil.today() +" "+ schedul.getStartTime()));
        if(0 <= clock){
            signVo.setClock("迟到");
        }else {
            signVo.setClock("正常");
        }
        int noon = parse.compareTo(DateUtil.parse(DateUtil.today()+" "+"12:00:00"));
        if(0 >= noon){
            signVo.setShiftop("1");
        }else {
            signVo.setShiftop("2");
        }
        if(Constant.Post.Night.getVal().equals(signVo.getJobName())){
            signVo.setShiftop("3");
        }
        boolean save = iSignService.save(signVo);
        return save? ResultUtils.resultBeansSuccess("签到成功"):ResultUtils.resultBeansError("签到失败");
    }
    @ApiOperation("返回签到状态")
    @PostMapping("/status")
    @ViLog(logType = "1",module =SwaggerTagConst.Admin.MANAGER_APP_SIGN,content = "返回签到状态")
    public ResultBeans status(@RequestBody SignVo signVo){
        Sign data = iSignService.getOne(Wrappers.<Sign>lambdaQuery()
                .eq(Sign::getPoliceId, signVo.getPoliceId())
                .eq(Sign::getState, 1), false);
        return ResultUtils.resultBeansSuccess(data);
    }
    /**
     * 签退（自动签退）
     */
    @ApiOperation("签退接口")
    @PostMapping("/out")
    @ViLog(logType = "1",module =SwaggerTagConst.Admin.MANAGER_APP_SIGN,content = "签退接口")
    public ResultBeans signOut(@RequestBody SignVo signVo){
        //签退状态
        signVo.setState(2);
        //签退时间
        signVo.setSignouttime(DateUtil.now());
        //判断季节是冬季还是夏季
        String season = getSeason();
        Schedul schedul = iSchedulService.getOne(Wrappers.<Schedul>lambdaQuery().eq(Schedul::getPost, signVo.getJobName())
                .eq(Schedul::getShiftop,signVo.getShiftop())
                .like(Schedul::getSeason, season),false);
        String endTime = schedul.getEndTime();
        String duty = DateUtil.today() + " " + endTime;
        DateTime parse = DateUtil.parse(duty);
        int compare = parse.compareTo(DateUtil.parse(signVo.getSignouttime()));
        if(compare >= 0){
            signVo.setSignOutClock("早退");
        }else {
            signVo.setSignOutClock("正常");
        }
        boolean update = iSignService.updateById(signVo);
        return update?ResultUtils.resultBeansSuccess("签退成功"):ResultUtils.resultBeansError("签退失败");
    }
    /**
     * 判断冬季还是夏季
     * @return 季节
     */
    private String getSeason(){
        int month = DateUtil.thisMonth()+1;
        Month monthEnum = Month.getTypeByValue(month);
        return monthEnum.getSeason();
    }

    /**
     * 判断是否签到
     * @param signVo 封装参数
     * @return boolean
     */
    private boolean isSign(SignVo signVo){
        Sign one = iSignService.getOne(Wrappers.<Sign>lambdaQuery().eq(Sign::getPoliceId, signVo.getPoliceId()).eq(Sign::getState, 1), false);
        return null != one;
    }


    /**
     * 推送长峰科技
     * @param signVo 封装参数
     */
    private void pushCfkj(SignVo signVo){
        Dept byId = iDeptService.getById(signVo.getSectionid());
        SysUser user = iSysUserService.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getWarningsignal,signVo.getPoliceId()));
        Jobs jobs = iJobsService.getById(signVo.getAssignmentid());
        try {
            Map<String,Object> map = new HashMap<>(7);
            String[] gps = signVo.getSignInGps().split(",");
            
            map.put("qdlat", gps[0]);
            map.put("qdlng", gps[1]);
            map.put("rwid", jobs.getRwid());
            map.put("userid", signVo.getPoliceId());
            map.put("zw", signVo.getAssignmentname());
            map.put("zzjgdm", byId.getCode());
            map.put("username", user.getUsername());
            String paramString = JSON.toJSONString(map);
            String result = HttpUtil.post(Constant.Url.signInUrl.getUrl() + "signIn", paramString);
            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONObject qwQdzxb = jsonObject.getJSONObject("qwQdzxb");
            String qdid = qwQdzxb.getString("qdid");
            signVo.setQdid(qdid);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("接口推送失败");
        }
    }
}

